<?php
  include_once('colMapping.php');

  $sort_by = 'parcelnum';
  foreach ($cols as $key => $value) {
    if ($_REQUEST['sort'] == $value) {
      $sort_by = $key;
    }
  }

  $sort_dir = 'A';
  if ($_REQUEST['dir'] == 'DESC') {
    $sort_dir = 'D';
  }

  $operator = '>';
  if (isset($_REQUEST['operator'])) {
    $operator = $_REQUEST['operator'];
  }
  // flip the sort_dir if sorting by credit removal
  if ($_REQUEST['sort'] == 'Credit Removal (lb/yr)' && $_REQUEST['operator'] == '<') {
    $sort_dir = $sort_dir == 'A' ? 'D' : 'A'; 
  }

  $xml = simplexml_load_string(file_get_contents("http://geo.bluecityexchange.org/geoserver/crwa/ows?service=WFS&version=1.1.0&request=GetFeature&typeName=crwa:parcels&cql_filter=regulated='True'+and+crdrem_lby+$operator+0&sortBy=$sort_by+$sort_dir&propertyName=parcelnum,ownername,crdrem_lby,town,cost_d,cost_d_lby,phys_addr1,phys_city,phys_st,phys_zip"));
  $data = array();
  foreach ($xml->xpath("gml:featureMembers/crwa:parcels") as $node) {
    $parcelnum  = $node->xpath('crwa:parcelnum');
    $ownername  = $node->xpath('crwa:ownername');
    $town       = $node->xpath('crwa:town');
    $crdrem_lby = $node->xpath('crwa:crdrem_lby');
    $cost_d     = $node->xpath('crwa:cost_d');
    $cost_d_lby = $node->xpath('crwa:cost_d_lby'); 
    $phys_addr1 = $node->xpath('crwa:phys_addr1');
    $phys_city  = $node->xpath('crwa:phys_city');
    $phys_st    = $node->xpath('crwa:phys_st');
    $phys_zip   = $node->xpath('crwa:phys_zip');

    $data[] = array(
       $cols['parcelnum']  => (string)$parcelnum[0]
      ,$cols['ownername']  => (string)$ownername[0]
      ,$cols['crdrem_lby'] => (string)$crdrem_lby[0]
      ,$cols['town']       => (string)$town[0]
      ,$cols['cost_d']     => (string)$cost_d[0]
      ,$cols['cost_d_lby'] => (string)$cost_d_lby[0]
      ,$cols['phys_addr1'] => (string)$phys_addr1[0]
      ,$cols['phys_city']  => (string)$phys_city[0]
      ,$cols['phys_st']    => (string)$phys_st[0]
      ,$cols['phys_zip']   => (string)$phys_zip[0]
    );
  }

  echo json_encode(array('data' => $data,'connt' => count($data)));
?>
